<template>
	<view class="indexPage">
		<!-- <view class="header" :style="{paddingTop:`${menuButton.top}rpx`}">
			深食堂
		</view> -->
		<!-- <button @click="login">登录</button> -->
		<!-- 头部-->
		<div class="backgroundImage">
			<image :src="indexData.headImageUrl" mode="aspectFill"></image>
		</div>

		<!-- 内容 -->
		<view class="content">
			<view class="info">
				<view class="info_top">
					<view>
						<image class="headPortrait" :src="headPortrait"></image>
						<div class="userInfo">
							<template v-if="token">
								<text>
									{{indexData.userName || ''}}
								</text>
								<text class="userId">余额:{{indexData.balance || 0}}</text>
							</template>

							<text v-else class="bgLogin" @click="loginInitData">点击登录</text>
						</div>
					</view>
					<view class="historyOrders" @click="goOrigin">历史订单</view>
				</view>
				<!-- <view class="info_bottom"> -->
				<!--	<view @click="goCoupons"> 
				 <view>优惠券</view>
						<text>{{indexData.couponCount}}</text>
					</view>
					<view @click="goPointsDetails">
						<view>积分</view>
						<text>{{indexData.points}}</text>
					</view> -->
				<!-- 	<view @click="goRecharge">
						<view>余额</view>
						<text>{{indexData.balance || 0}}</text>
					</view>
				</view> -->
			</view>
			<view class="promotional_image">
				<view class="left" @click="goStoreDetails">
					<image :src="indexData.middleImageUrl" mode="aspectFill"></image>
				</view>
				<view class="right" @click="goStoreDetails">
					<image src="/static/placeAnOrder.png"></image>
					<view>外卖</view>
					<text>( 下单进入 )</text>
				</view>
			</view>
			<view class="uni-margin-wrap">
				<swiper class="swiper" circular :indicator-dots="true" :autoplay="true" interval="2000" duration="500">
					<swiper-item v-for="item in indexData.noteImagesUrl">
						<image mode="aspectFit" :src="item"></image>
					</swiper-item>
				</swiper>
			</view>
		</view>

		<!-- 小程序登录 -->
		<login @loginSuccess="loginSuccess" :auth.sync="auth"></login>
		<!-- 新手大礼包 -->
		<!-- <newUserCouponPackage @receiveFn="queryWelcomePageDataFn" ref="newUserCouponPackage" :newUserCouponPackage="newUserCouponPackage">
		</newUserCouponPackage> -->

		<!-- 加载动画 -->
		<loading :showLoading="showLoading" text="数据加载中"></loading>
		<custom-tab-bar :items="tabItems" :currentIndex="currentTab" @item-click="onTabClick" :color="color"
			:selectedColor="selectedColor"></custom-tab-bar>
	</view>
</template>

<script>
	import MyMinix from '@/utils/minix/minix.js';
	import util from "@/utils/util.js";
	import CustomTabBar from '@/uni_modules/niceui-tabBar/components/niceui-tabBar/niceui-tabBar.vue';
	import tabbar from '@/uni_modules/niceui-tabBar/common/tabbar.js'
	import {
		mapState,
		mapGetters
	} from 'vuex'
	import {
		queryBuildingBriefInfoBySiteId,
		queryNearnestSiteAddrByLongLat,
		queryStoresByKeyword,
		queryWelcomePageData,
		checkNewUserCouponPackage,
		queryAllSiteAddress
	} from "@/request/api.js";
	export default {
		mixins: [MyMinix],
		components: {
			CustomTabBar
		},
		data() {
			return {
				util, //公共方法
				showLoading: false, //显示加载动画
				bannerList: [], //轮播图
				loadingImg: '../../static/loading.png',
				headPortrait: '../../static/user.png',
				// 小程序授权弹窗 false 不显示 true 显示 
				auth: false,
				indexData: {
					nickName: '',
					couponCount: 0,
					points: 0,
					wallet: 0,
					headImageUrl:'https://customer.qiyetuancan.com/static/images/carousels/homepage_background_image.jpg',
					middleImageUrl:'https://customer.qiyetuancan.com/static/images/carousels/homepage_background_image2.jpg',
					noteImagesUrl:['https://customer.qiyetuancan.com/static/images/carousels/carousel_1.jpg'],
				

					carousels: [], //轮播图
				},
				newUserCouponPackage: {}, //判断是否为新用户信息
				myAddress: {},
				currentTab: 0, // 当前选中的tab索引
				tabItems: tabbar.tabItems,
				color: tabbar.color,
				selectedColor: tabbar.selectedColor,
				token: '',
				menuButton: {}

			}
		},
		onShareAppMessage() {
			return {
				title: '祥瑜团餐',
				path: '/pages/index/index',
				imageUrl: ''
			}
		},
		// 只有首次进入 执行一次，后续不执行
		async onLoad(options) {
			// 获取旧用户 id 绑定
			if (options.scene) {
				uni.setStorageSync('sharedUserId', decodeURIComponent(options.scene).split('=')[1]);
				uni.getStorageSync('token') && util.sendSharedUserIdFn();
			}

			// 获取选择的地址
			let datas = util.getStorePage();
			let currAddress = datas['currAddress'];
			// 获取当前位置最匹配的大厦
			if (!currAddress) {
				// await this.getAddressAuth();
			} else {
				this.myAddress = currAddress
				// this.initStoreData()
			}
		},
		// 每次进入首页都会执行
		async onShow() {
			this.token = uni.getStorageSync('token');
			this.menuButton = util.getMenuButton()
			this.initData()
		},
		methods: {
			// 
			onTabClick(index) { // 切换tab的函数，当选中某个tab时触发  
				//this.currentTab = index;  
				if (index != this.currentTab) {
					util.goToUrl(this.tabItems[index].pagePath)
				}

			},

			// 获取首页背景图，轮播图，用户昵称，余额，优惠券，积分等信息
			async queryWelcomePageDataFn() {
				// let phoneNumber = uni.getStorageSync('phoneNumber');
				let userInfo = uni.getStorageSync('userInfo');
				if(!userInfo ||  !userInfo?.phoneNumber) {
					uni.showToast({
						title:"未登录,请先登录!",
						icon:'none'
					})
					return
				};
				let res = await queryWelcomePageData({
					method: "get",
					data: userInfo.phoneNumber ? {
						phoneNumber: userInfo.phoneNumber
					} : {}
				});
				if (res.code == 200) {
					this.indexData = res.data;
					// this.indexData = {
					// 	...res.data,
					// 	headImageUrl:'https://customer.qiyetuancan.com/static/images/carousels/homepage_background_image.jpg',
					// 	middleImageUrl:'https://customer.qiyetuancan.com/static/images/carousels/homepage_background_image2.jpg',
					// 	noteImagesUrl:['https://customer.qiyetuancan.com/static/images/carousels/carousel_1.jpg','https://customer.qiyetuancan.com/static/images/carousels/carousel_1.jpg']
					// 	// 
					// }
				}

			},

			// 判断是否登录
			login() {
				let token = uni.getStorageSync('token');
				if (!token) {
					this.auth = true;
				}
				return token;
			},
			loginInitData() {
				if (this.login()) {
					this.initData();
				}
			},
			// 登录成功 隐藏登录弹窗 初始化数据
			loginSuccess() {
				this.auth = false;
				this.token = uni.getStorageSync('token');
				this.initData();
			},

			// 跳转历史订单
			goOrigin() {
				if (this.login()) {
					util.goToUrl('/pages/myPage/delCenter/delCenter?status=0')
				}

			},
			// 去充值
			goRecharge() {
				if (this.login()) {
					util.goToUrl('/pages/recharge/recharge')
				}
			},




			// 去点餐
			goStoreDetails() {
				util.goToUrl('/pages/storeList/storeList')
			},







			// 初始数据
			async initData() {
				this.showLoading = true;
				let token = uni.getStorageSync('token');
				// 获取首页背景图，轮播图，用户昵称，余额，优惠券，积分等信息
				this.queryWelcomePageDataFn();
				if (token) {
					// 判断是否为新用户
					// this.checkNewUserCouponPackageFn();
				}
				this.showLoading = false;
			},









			// 暂无使用

			// 初始数据
			async initStoreData() {
				this.showLoading = true;

				let token = uni.getStorageSync('token');

				// 获取地址列表
				// this.queryAllSiteAddressFn();

				//根据店铺或菜品名进行模糊搜索
				// this.queryStoresByKeywordFn();

				// 根据站点id获取站点下的大厦列表和按钮icon图标
				// this.queryBuildingBriefInfoBySiteIdFn();
				if (token) {
					// 购物车列表
					// this.getShopCar();
				}
				this.showLoading = false;


			},




			// 积分详情
			goPointsDetails() {
				return;
				if (this.login()) {
					util.goToUrl('/pages/myPage/pointsDetails/pointsDetails')
				}
			},

			// 优惠券
			goCoupons() {
				if (this.login()) {
					util.goToUrl('/pages/myPage/myCoupons/index/index')
				}
			},

			//获取是否为新用户
			async checkNewUserCouponPackageFn() {
				let datas = util.getStorePage();
				let currAddress = datas['currAddress'];
				let res = await checkNewUserCouponPackage({
					method: "GET",
					data: {
						siteId: currAddress ? currAddress.addressId : ''
					}
				})
				let result = res.result;
				this.newUserCouponPackage = result;
				// 如果是新用户 显示弹窗
				if (result.received == 0) {
					this.$refs.newUserCouponPackage.showPopup();
				}
			},


			// 下单页面接口

			// 判断是否有获取当前位置权限 ， 如果有直接获取，没有则需要用户点击授权
			async getAddressAuth() {
				let that = this;
				// 获取用户是否开启 授权获取当前的地理位置、速度的权限。
				await uni.getSetting({
					success: async (res) => {
						// 如果没有授权
						if (!res.authSetting['scope.userLocation']) {
							// 则拉起授权窗口
							uni.authorize({
								scope: 'scope.userLocation',
								success: async (res) => {
									//点击允许后--就一直会进入成功授权的回调 就可以使用获取的方法了
									await that.getTheCurrentAddress();
								}
							})
						} else {
							await that.getTheCurrentAddress();
						}
					}
				})
			},

			// 根据经纬度 获取距离最近的大厦
			async queryNearnestSiteAddrByLongLatFn() {
				let address = await queryNearnestSiteAddrByLongLat({
					method: "GET",
					data: {
						latitude: this.latlon.latitude,
						longitude: this.latlon.longitude
					},
				})
				this.myAddress.addressId = address.result.nearnestAddrId;
				this.myAddress.addressName = address.result.nearnestAddrName;
				util.setStorePage([{
					name: 'currAddress',
					data: this.myAddress
				}]);
				this.initStoreData();
			},

			// 获取地址列表
			async queryAllSiteAddressFn() {
				let datas = this.getStorePage();
				let addressList = datas['addressList']
				if (addressList) {
					return;
				}
				let res = await queryAllSiteAddress({
					method: "GET",
				})
				util.setStorePage([{
					name: 'addressList',
					data: res.result.allAddress
				}]);
			},
			// 获取当前位置最匹配的大厦
			async getTheCurrentAddress() {
				let that = this;
				await uni.getLocation({
					type: 'gcj02',
					// type: 'wgs84',
					geocode: true,
					highAccuracyExpireTime: 6000,
					isHighAccuracy: true, //是否开启高精度
					success: async function(res) {
						let latlon = {
							latitude: res.latitude,
							longitude: res.longitude
						}
						that.latlon = latlon;
						// 根据经纬度 获取距离最近的大厦
						that.queryNearnestSiteAddrByLongLatFn();
					},
					fail: function(err) {
						console.log(err, 'err');
					}
				});
			},

			/** 根据店铺名或菜品名进行模糊搜索
			 **/
			async queryStoresByKeywordFn() {
				let res = await queryStoresByKeyword({
					method: "GET",
					data: {
						siteAddrId: this.myAddress.addressId, //用户办公地点大厦Id，由接口1.1自动定位 或 1.2 用户手动选择的大厦的Id；
						keyword: '', //在搜索框中输入的关键字，菜品名称或部分，用户没有在输入框中输入搜索条件时，此字段传递null 即可；
						pageNo: 1, //从1开始，分页查询
						pageSize: 10 //每页数据行数，比如10
					}
				});

				if (res.code == 200) {
					this.setShopList(res.result);
				}

			},

			// 设置店铺列表信息
			setShopList(data) {
				let shopList = [],
					shopBusinessTime = [];
				data.forEach(item => {
					item.businessHours = JSON.stringify([{
						startTime: item.businessHoursBegin,
						endTime: item.businessHoursEnd
					}])
					item.businessTime = item.businessHoursBegin + '~' + item.businessHoursEnd;
					shopBusinessTime.push({
						storeId: item.storeId,
						storeName: item.storeName,
						businessTime: item.businessTime
					})
					shopList.push(item);
				});
				util.setStorePage([{
						name: 'storeList',
						data: shopList
					},
					{
						name: 'shopBusinessTime',
						data: shopBusinessTime
					},
				]);
			},


			// 根据站点id获取站点下的大厦列表和按钮icon图标
			async queryBuildingBriefInfoBySiteIdFn() {
				let res = await queryBuildingBriefInfoBySiteId({
					method: "GET",
					data: {
						siteId: this.myAddress.addressId, //用户所在大厦Id；
					}
				});
				if (res.code == 200) {
					let build = res.result.buildings;
					util.setStorePage([{
						name: 'buildingsList',
						data: build
					}, ]);
				}
			},



		}
	}
</script>

<style lang="scss" scoped>
	.header {
		font-size: 32rpx;
		font-weight: 600;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		text-align: center;
	}

	.indexPage {
		padding-bottom: 120rpx;
	}

	// 头部
	.backgroundImage {
		height: 628rpx;
		width: 100%;

		image {
			display: block;
			width: 100%;
			height: 100%;
		}
	}

	.content {
		padding-bottom: 30rpx;
	}

	.userInfo {
		display: flex;
		align-items: flex-start;
		flex-direction: column;

		.userId {
			margin-top: 15rpx;
			color: rgba(102, 102, 102, 1);
			font-family: PingFang SC;
			font-weight: 500;
			font-size: 22rpx;
		}
	}

	.info {
		background: #fff;
		padding: 30rpx;
		margin: -92rpx 30rpx 30rpx;
		border-radius: 20rpx;
		// box-shadow: 0 0 5rpx 5rpx rgba(0, 0, 0, .1);
		box-shadow: 0px 0px 16rpx rgba(235, 91, 30, 0.2);

		&_top {
			@include flexs(space-between, center);
			font-size: 28rpx;

			// margin-bottom:20rpx;
			// padding-bottom:14rpx;
			// border-bottom:1rpx solid #EEEEEE;
			&>view:nth-child(1) {
				@include flexs(space-between, center);
			}

			.headPortrait {
				width: 104rpx;
				height: 104rpx;
				margin-right: 20rpx;
			}


			.historyOrders {
				background: #EB5B1E;
				width: 144rpx;
				height: 64rpx;
				line-height: 64rpx;
				color: #fff;
				text-align: center;
				border-radius: 32rpx;
			}

			.bgLogin {
				font-size: 28rpx;
				color: #333;
				height: 50rpx;
				line-height: 50rpx;
				text-align: center;
				border: 1rpx solid #333;
				border-radius: 50rpx;
				padding: 0 20rpx;
			}
		}

		&_bottom {
			@include flexs(space-between, center);
			padding-top: 10rpx;

			&>view {
				flex: 1;
				@include flexs(center, center);
				flex-direction: column;
				border-right: 2rpx solid #EEEEEE;

				&:last-child {
					border: none;
				}

				view {
					font-size: 24rpx;
					margin-bottom: 12rpx;
				}

				text {
					font-size: 28rpx;
				}
			}

		}

		// justify-content: space-between;
	}

	.promotional_image {
		@include flexs(space-between, center);
		margin: 0 30rpx 30rpx;


		&>view {
			width: 330rpx;
			height: 250rpx;
			border-radius: 20rpx;
		}

		.left {
			// width: calc(100% - 200rpx);
			// height: 200rpx;

			box-shadow: 0px 0px 16rpx rgba(235, 91, 30, 0.2);

			image {
				display: block;
				width: 100%;
				height: 100%;
				border-radius: 20rpx;
			}
		}

		.right {
			position: relative;
			// width: 200rpx;
			// height: 200rpx;
			text-align: center;
			@include flexs(center, center);
			flex-direction: column;
			// background-image: url("../../static/placeAnOrder.png");
			// background-size: 100% 100%;
			// background-repeat: no-repeat;
			box-shadow: 0px 0px 16rpx rgba(235, 91, 30, 0.2);

			image {
				position: absolute;
				top: 0;
				left: 0;
				width: 100%;
				height: 100%;
				z-index: -1;
			}

			&>view {
				font-size: 40rpx;
				font-weight: 600;
				color: #EB5B1E;
				margin-bottom: 20rpx;
			}

			text {
				font-size: 28rpx;
				color: #000;
			}
		}
	}

	.uni-margin-wrap {
		box-shadow: 0px 0px 16rpx rgba(235, 91, 30, 0.2);
		margin: 0 30rpx;
		border-radius: 20rpx;
	}

	.swiper {
		height: 280rpx;
		overflow: hidden;

		image {
			display: block;
			width: 100%;
			height: 100%;
		}
	}
</style>